
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "errlog.h"

unsigned parse_patches_infile(const char *fname, unsigned *codes, char **names,
        unsigned max_patches, unsigned max_name_length)
{
    unsigned count = 0;
    unsigned line_size = 255;
    char *line = calloc(line_size + 1, sizeof (char));
    FILE *file = fopen(fname, "r");
    if(file == NULL)
        error_msg("cannot open file '%s' for reading.\n", fname);
    while(fgets(line, line_size, file))
    {
        char *toc = strtok(line, " \t\n:");
        if(toc == NULL)
            continue;
        strncpy(names[count], toc, max_name_length);
        names[count][max_name_length - 1] = '\0';
        codes[count] = 0;
        while((toc = strtok(NULL, " \t\n:,;")) != NULL)
        {
            unsigned val = atoi(toc);
            if(val < 0 || val >= 8 * sizeof (unsigned))
                goto error;
            codes[count] |= 1 << val;
        }
        ++count;
        if(count >= max_patches)
            break;
    }
    free(line);
    fclose(file);

    return count;

error:
    error_msg("could not parse line %d of file '%s'.\n", count, fname);
}

